<template>
  <div id="qcMaterialTargetDiv">
    <Breadcrumb content="质控品靶值" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="30">
          <!-- 质控靶值设定  -->
          <div class="saveBtn">
            <vxe-checkbox v-model="searchForm.isShowAll" size="small" content="显示过期的质控品" checked-value="1" unchecked-value="0" @change="findMaterialItemTree"></vxe-checkbox>
          </div>
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">仪器</div>
              <vxe-select v-model="searchForm.instrIds" multiple :filterable="true" clearable @change="valueChangeEvent">
                <vxe-option v-for="instr in instrList" :key="instr.id" :value="instr.id" :label="instr.instrName"></vxe-option>
              </vxe-select>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="treeloading" @click="findMaterialItemTree"></vxe-button>
            </template>
          </vxe-toolbar>
          <el-scrollbar style="height: calc(100% - 40px)">
            <div class="sampleType">
              <el-scrollbar>
                <el-tree :expand-on-click-node="false" :default-expanded-keys="expandedkeys" :data="materialItemTree" :props="defaultProps" node-key="id" ref="dataTreeRef" highlight-current class="tools-tree" @node-click="handleClickType" v-loading="treeloading">
                  <template #default="{ data, node }">
                    <div style="float: right">
                      <img :src="`${getAssetsFile('images/qc/' + data.type + '.png')}`" style="width: 15px; height: 15px; margin-right: 10px" />
                      {{ data.name }}
                    </div>
                  </template>
                </el-tree>
              </el-scrollbar>
            </div>
          </el-scrollbar>
        </Pane>
        <Pane size="70">
          <el-tabs type="border-card">
            <el-tab-pane label="靶值设定" v-if="(sltMaterItem&&sltMaterItem.itemDefine=='dl')||IsEmpty(sltMaterItem)">
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class="smallToolTitle">质控靶值设定</div>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="iloading" :disabled="disabledTag" @click="findMaterialTargetList"></vxe-button>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" :disabled="disabledTag" @click="addMaterialTarget"></vxe-button>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :disabled="disabledTag" :loading="sloading" @click="saveMaterialTargetList"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="disabledTag" @click="deleteMaterialTarget"></vxe-button>
                  <div class="saveBtn">
                    <vxe-checkbox v-model="jsJgFlag" size="small" content="是否重新计算结果" checked-value="1" unchecked-value="0" :disabled="disabledTag"></vxe-checkbox>
                  </div>
                </template>
              </vxe-toolbar>
              <div class="tableBox">
                <vxe-table ref="materialTargetTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="materialTargetList" :loading="iloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
                  <vxe-column type="checkbox" width="30" align="center"></vxe-column>

                  <vxe-column field="enableDate" title="启用日期" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.enableDate" placeholder="日期选择" type="date"></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="mean" title="靶值" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.mean" type="number"></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="sd" title="SD" width="150" :edit-render="{}" c>
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.sd" type="number" style="width:60%;display:inline-block;"></vxe-input>
                      <div style="width:40%;display:inline-block;">
                        <vxe-button class="compute-button" content="计算CV" @click.native="computeCV(row)">
                        </vxe-button>
                      </div>
                    </template>
                  </vxe-column>
                  <vxe-column field="cv" title="CV" width="150" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.cv" type="number" style="width:60%;display:inline-block;"></vxe-input>
                      <div style="width:40%;display:inline-block;">
                        <vxe-button class="compute-button" content="计算sd" @click.native="computeSD(row)">
                        </vxe-button>
                      </div>
                    </template>
                  </vxe-column>
                  <vxe-column field="outUpper" title="失控上限" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.outUpper" type="number"></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="outLower" title="失控下限" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.outLower" type="number"></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="reagentSupplier" title="试剂供应商" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.reagentSupplier" type="text" clearable></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="reagentBatchNum" title="试剂批号" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.reagentBatchNum" type="text" clearable></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="caliManu" title="校准品厂商" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.caliManu" type="text" clearable></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="caliBatchNum" title="校准品批号" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.caliBatchNum" type="text" clearable></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="reagentManu" title="试剂厂商" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.reagentManu" type="text" clearable></vxe-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="method" title="方法学" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.method" type="text" clearable></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="changeReason" title="更换靶值原因" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.changeReason" type="text" clearable></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="stopDate" title="停用日期" width="100" :edit-render="{}">
                    <template #default="{ row }">
                      <span>{{ formatDateNYR(row) }}</span>
                    </template>
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.stopDate" placeholder="日期选择" type="date" clearable transfer></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="stopOperator" title="停用操作者" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.stopOperator" disabled type="text"></vxe-input>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>
            </el-tab-pane>

            <el-tab-pane label="定性设定" v-if="sltMaterItem&&sltMaterItem.itemDefine=='dx'">
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class="smallToolTitle">定性结果设定</div>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="iloading" :disabled="disabledTag" @click="findMaterialFixedList"></vxe-button>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" :disabled="disabledTag" @click="addMaterialFixed"></vxe-button>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :disabled="disabledTag" :loading="sloading" @click="saveMaterialFixedList"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="disabledTag" @click="deleteMaterialFixed"></vxe-button>
                  <!-- <div class="saveBtn">
                    <vxe-checkbox v-model="jsJgFlag" size="small" content="是否重新计算结果" checked-value="1" unchecked-value="0" :disabled="disabledTag"></vxe-checkbox>
                  </div> -->
                </template>
              </vxe-toolbar>
              <div class="tableBox">
                <vxe-table ref="materialFixedTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="materialFixedList" :loading="iloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
                  <vxe-column type="checkbox" width="30" align="center"></vxe-column>

                  <vxe-column field="enableDate" title="启用日期" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.enableDate" placeholder="日期选择" type="date"></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="result" title="质控结果" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.result" type="text" clearable></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="numResult" title="数值结果" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.numResult" type="text" clearable></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="z" title="Z分数值" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.z" type="text" clearable></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="isAlarm" title="是否警告" width="100" :edit-render="{}">
                    <template #default="{ row }">
                      <el-tag :type="row.isAlarm ? 'success' : 'danger'">
                        {{ row.isAlarm ? '是' : '否' }}
                      </el-tag>
                    </template>
                    <template #edit="{ row }">
                      <vxe-switch v-model="row.isAlarm" open-label="是" close-label="否"></vxe-switch>
                    </template>
                  </vxe-column>
                  <vxe-column field="isOutControl" title="是否失控" width="100" :edit-render="{}">
                    <template #default="{ row }">
                      <el-tag :type="row.isOutControl ? 'success' : 'danger'">{{ row.isOutControl ? '是' : '否' }}
                      </el-tag>
                    </template>
                    <template #edit="{ row }">
                      <vxe-switch v-model="row.isOutControl" open-label="是" close-label="否"></vxe-switch>
                    </template>
                  </vxe-column>
                  <vxe-column field="stopDate" title="停用日期" width="100" :edit-render="{}">
                    <template #default="{ row }">
                      <span>{{ formatDateNYR(row) }}</span>
                    </template>
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.stopDate" placeholder="日期选择" type="date" clearable transfer></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="stopOperator" title="停用操作者" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.stopOperator" disabled type="text"></vxe-input>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>
            </el-tab-pane>
            <el-tab-pane label="操作日志">
              <LogInfo requestUrl="/api/qc/qcMaterialItemTarget"></LogInfo>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import moment from 'moment';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { getAssetsFile } from '@/utils/common';
import { AppStore } from '@/stores/store';
import { isEmpty } from 'lodash';
//import { fa } from 'element-plus/es/locale';
import LogInfo from '@/components/LogInfo.vue'; //操作日志

// 全局变量定义区 ==========
let store = AppStore();
let { proxy }: any = getCurrentInstance();
// 加载状态
let treeloading = ref(false); //质控靶值树上的刷新
let materialItemTree: any = reactive([]); //最左侧质控靶值设定树数据
let instrList: any = reactive([]); //左侧仪器下拉项
// 最左侧的树
let defaultProps = {
  children: 'children',
  label: 'name'
};
let sltMaterItem: any = ref({});
let iloading = ref(false); //质控靶值设定 刷新+表格数据
let sloading = ref(false);
let materialTargetList: any = reactive([]); //质控项目设定表格数据
let materialFixedList: any = reactive([]); //质控项目设定表格数据

let expandedkeys: any = reactive([]);
let disabledTag = ref(true);
let jsJgFlag = ref('0');
let searchForm = ref({
  searchValue: '',
  instrId: '',
  instrIds: [],
  isShowAll: '0'
});

// 方法定义区 =============
// 页面加载时更新
onMounted(() => {
  findInstrSetupList();
  findMaterialItemTree(); // 获取最左侧质控靶值树数据
});

// 获取左侧仪器下拉选项数据(标题)
function findInstrSetupList() {
  instrList.length = 0; //放入数据前清空数据
  const url = '/lis/instrSetup/getInstrSetupList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: '', poct: 1 }
    })
    .then((res: any) => {
      instrList.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage('获取左侧仪器表格数据异常', VxeNotifyType.error);
    });
}

// 仪器下拉选择 改变
function valueChangeEvent() {
  findMaterialItemTree();
}

// 获取最左侧质控靶值树 刷新
function findMaterialItemTree() {
  treeloading.value = true;
  materialItemTree.length = 0; //放入数据前清空数据
  expandedkeys.length = 0;
  const url = '/api/qc/qcMaterialItem/findMaterialItemTree';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { isShowAll: searchForm.value.isShowAll, instrIds: searchForm.value.instrIds, poct: 1 } })
    .then((res: any) => {
      if (!IsEmpty(res.data)) {
        materialItemTree.push(...res.data);
        getExpandedkeys();
        materialTargetList.length = 0;
        sltMaterItem.value = {};
        //如果点击的当前行数据是父级，那就禁用质控品维护的按钮
        if (!sltMaterItem.value.id) {
          disabledTag.value = true;
        } else {
          //如果点击的当前行数据是子集，那就不需要禁用质控品维护的按钮
          disabledTag.value = false;
        }
      }
      treeloading.value = false;
    })
    .catch((err: any) => {
      treeloading.value = false;
      VxeMessage('获取最左侧质控靶值树异常', VxeNotifyType.error);
    });
}

//点击左侧树
function handleClickType(obj: any, node: any, data: any) {
  const isSearch = obj.isSearch;
  if (isSearch == '0') {
    sltMaterItem.value = obj;
    console.log(sltMaterItem.value);

    if (sltMaterItem.value.itemDefine == 'dl') {
      findMaterialTargetList();
    } else if (sltMaterItem.value.itemDefine == 'dx') {
      findMaterialFixedList();
    }
  } else {
    materialTargetList.length = 0;
    sltMaterItem.value = {};
  }
  //如果点击的当前行数据是父级，那就禁用质控品维护的按钮
  if (!sltMaterItem.value.id) {
    disabledTag.value = true;
  } else {
    //如果点击的当前行数据是子集，那就不需要禁用质控品维护的按钮
    disabledTag.value = false;
  }
}

// 获取质控靶值设定表格数据 刷新
function findMaterialTargetList() {
  iloading.value = true;
  materialTargetList.length = 0; //放入数据前清空数据
  const url = '/api/qc/qcMaterialItemTarget/findMaterialTargetList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { pid: sltMaterItem.value.id }
    })
    .then((res: any) => {
      materialTargetList.push(...res.data);
      iloading.value = false;
    })
    .catch((err: any) => {
      iloading.value = false;
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });
}

// 新增质控靶值设定表格数据
function addMaterialTarget() {
  if (isEmpty(sltMaterItem.value)) {
    VxeMessage('请选择质控项目', VxeNotifyType.error);
  } else {
    const record = {
      id: '',
      materialItemId: sltMaterItem.value.id,
      materialId: sltMaterItem.value.materialId,
      qcItemId: sltMaterItem.value.qcItemId,
      instrId: sltMaterItem.value.instrId,
      itemDictId: sltMaterItem.value.itemDictId,
      enableDate: sltMaterItem.value.enableDate,
      seq: materialTargetList.length + 1 //排序号
    };
    materialTargetList.push(record);
  }
}

// 保存质控靶值设定表格数据
async function saveMaterialTargetList() {
  if (isEmpty(sltMaterItem.value)) {
    VxeMessage('请选择质控项目', VxeNotifyType.error);
  } else {
    let $Xtable = proxy.$refs.materialTargetTableRef;
    if ($Xtable) {
      sloading.value = true;
      // 表格实例表用该方法拿到有id的为修改
      const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
        return p.id && p.id !== '';
      });
      // 拿到数组中没有id的数据为新增
      const InsertRecords = materialTargetList.filter((e: any) => {
        return !e.id || e.id === '';
      });

      const sveOrupdateitems = [] as any[];
      updateRecords.forEach((e: any) => {
        const maItem = {
          id: e.id,
          materialId: e.materialId,
          materialItemId: e.materialItemId,
          qcItemId: e.qcItemId,
          instrId: e.instrId,
          itemDictId: e.itemDictId,
          enableDate: e.enableDate,
          mean: e.mean,
          sd: e.sd,
          cv: e.cv,
          outUpper: e.outUpper,
          outLower: e.outLower,
          reagentBatchNum: e.reagentBatchNum,
          reagentSupplier: e.reagentSupplier,
          caliManu: e.caliManu,
          caliBatchNum: e.caliBatchNum,
          reagentManu: e.reagentManu,
          method: e.method,
          stopDate: e.stopDate,
          stopOperator: e.stopOperator,
          orgId: e.orgId,
          seq: e.seq
        };
        maItem.stopDate = isEmpty(maItem.stopDate) ? '' : maItem.stopDate + ' 23:59:59';
        sveOrupdateitems.push(maItem);
      });
      InsertRecords.forEach((e: any) => {
        const maItem = {
          id: e.id,
          materialId: e.materialId,
          materialItemId: e.materialItemId,
          qcItemId: e.qcItemId,
          instrId: e.instrId,
          itemDictId: e.itemDictId,
          enableDate: e.enableDate,
          mean: e.mean,
          sd: e.sd,
          cv: e.cv,
          outUpper: e.outUpper,
          outLower: e.outLower,
          reagentBatchNum: e.reagentBatchNum,
          reagentSupplier: e.reagentSupplier,
          caliManu: e.caliManu,
          caliBatchNum: e.caliBatchNum,
          reagentManu: e.reagentManu,
          method: e.method,
          stopDate: e.stopDate,
          stopOperator: e.stopOperator,
          orgId: store.userInfo.orgId,
          seq: e.seq
        };
        maItem.stopDate = isEmpty(maItem.stopDate) ? '' : maItem.stopDate + ' 23:59:59';
        sveOrupdateitems.push(maItem);
      });

      if (sveOrupdateitems.length > 0) {
        const url = '/api/qc/qcMaterialItemTarget/saveOrUpdateMaterialTarget';
        const obj: any = {};
        obj.materialTargetList = sveOrupdateitems;
        obj.jsJgFlag = jsJgFlag.value;
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            VxeMessage('修改成功', VxeNotifyType.success);
            setTimeout(() => {
              sloading.value = false;
              jsJgFlag.value = '0';
              findMaterialTargetList();
            }, 50);
          })
          .catch((err: any) => {
            sloading.value = false;
            VxeMessage('修改失败', VxeNotifyType.success);
          });
      } else {
        sloading.value = false;
        VxeMessage('无添加或修改数据', VxeNotifyType.error);
      }
    } else {
      return;
    }
  }
}
// 删除质控靶值设定表格数据
function deleteMaterialTarget() {
  const sltMaterialTargets = (proxy.$refs.materialTargetTableRef as any).getCheckboxRecords();
  if (!(sltMaterialTargets.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        //后台删除数据
        const delMaterialTargetList = sltMaterialTargets.filter((p: any) => !isEmpty(p.id));
        if (delMaterialTargetList.length > 0) {
          const data = { materialTargetList: delMaterialTargetList };
          const url = '/api/qc/qcMaterialItemTarget/batchDeleteMaterialTargetList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findMaterialTargetList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeMaterialTargetList = sltMaterialTargets.filter((p: any) => isEmpty(p.id));
        if (removeMaterialTargetList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.materialTargetTableRef;
          if ($Xtable) {
            for (const removeRow of removeMaterialTargetList) {
              const index = materialTargetList.findIndex((item: any) => item == removeRow);
              materialTargetList.splice(index, 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

// 获取质控靶值设定表格数据 刷新
function findMaterialFixedList() {
  iloading.value = true;
  materialFixedList.length = 0; //放入数据前清空数据
  const url = '/api/qc/qcMaterialItemFixed/findMaterialFixedList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { pid: sltMaterItem.value.id }
    })
    .then((res: any) => {
      materialFixedList.push(...res.data);
      iloading.value = false;
    })
    .catch((err: any) => {
      iloading.value = false;
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });
}

// 新增质控靶值设定表格数据
function addMaterialFixed() {
  if (isEmpty(sltMaterItem.value)) {
    VxeMessage('请选择质控项目', VxeNotifyType.error);
  } else {
    const record = {
      id: '',
      materialItemId: sltMaterItem.value.id,
      materialId: sltMaterItem.value.materialId,
      qcItemId: sltMaterItem.value.qcItemId,
      instrId: sltMaterItem.value.instrId,
      itemDictId: sltMaterItem.value.itemDictId,
      enableDate: sltMaterItem.value.enableDate,
      isAlarm: false,
      isOutControl: false,
      seq: materialFixedList.length + 1 //排序号
    };
    materialFixedList.push(record);
  }
}

// 保存质控靶值设定表格数据
async function saveMaterialFixedList() {
  if (isEmpty(sltMaterItem.value)) {
    VxeMessage('请选择质控项目', VxeNotifyType.error);
  } else {
    let $Xtable = proxy.$refs.materialFixedTableRef;
    if ($Xtable) {
      sloading.value = true;
      // 表格实例表用该方法拿到有id的为修改
      const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
        return p.id && p.id !== '';
      });
      // 拿到数组中没有id的数据为新增
      const InsertRecords = materialFixedList.filter((e: any) => {
        return !e.id || e.id === '';
      });

      const sveOrupdateitems = [] as any[];
      updateRecords.forEach((e: any) => {
        const maItem = {
          id: e.id,
          materialId: e.materialId,
          materialItemId: e.materialItemId,
          qcItemId: e.qcItemId,
          instrId: e.instrId,
          itemDictId: e.itemDictId,
          enableDate: e.enableDate,
          isAlarm: e.isAlarm,
          isOutControl: e.isOutControl,
          result: e.result,
          numResult: e.numResult,
          z: e.z,
          stopDate: e.stopDate,
          stopOperator: e.stopOperator,
          orgId: e.orgId,
          seq: e.seq
        };
        maItem.stopDate = isEmpty(maItem.stopDate) ? '' : maItem.stopDate + ' 23:59:59';
        sveOrupdateitems.push(maItem);
      });
      InsertRecords.forEach((e: any) => {
        const maItem = {
          id: e.id,
          materialId: e.materialId,
          materialItemId: e.materialItemId,
          qcItemId: e.qcItemId,
          instrId: e.instrId,
          itemDictId: e.itemDictId,
          enableDate: e.enableDate,
          isAlarm: e.isAlarm,
          isOutControl: e.isOutControl,
          result: e.result,
          numResult: e.numResult,
          z: e.z,
          stopDate: e.stopDate,
          stopOperator: e.stopOperator,
          orgId: store.userInfo.orgId,
          seq: e.seq
        };
        maItem.stopDate = isEmpty(maItem.stopDate) ? '' : maItem.stopDate + ' 23:59:59';
        sveOrupdateitems.push(maItem);
      });

      if (sveOrupdateitems.length > 0) {
        const url = '/api/qc/qcMaterialItemFixed/saveOrUpdateMaterialFixed';
        const obj: any = {};
        obj.materialFixedList = sveOrupdateitems;
        obj.jsJgFlag = jsJgFlag.value;
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            VxeMessage('修改成功', VxeNotifyType.success);
            setTimeout(() => {
              sloading.value = false;
              jsJgFlag.value = '0';
              findMaterialFixedList();
            }, 50);
          })
          .catch((err: any) => {
            sloading.value = false;
            VxeMessage('修改失败', VxeNotifyType.success);
          });
      } else {
        sloading.value = false;
        VxeMessage('无添加或修改数据', VxeNotifyType.error);
      }
    } else {
      return;
    }
  }
}
// 删除质控靶值设定表格数据
function deleteMaterialFixed() {
  const sltMaterialFixeds = (proxy.$refs.materialFixedTableRef as any).getCheckboxRecords();
  if (!(sltMaterialFixeds.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        //后台删除数据
        const delMaterialFixedList = sltMaterialFixeds.filter((p: any) => !isEmpty(p.id));
        if (delMaterialFixedList.length > 0) {
          const data = { materialFixedList: delMaterialFixedList };
          const url = '/api/qc/qcMaterialItemFixed/batchDeleteMaterialFixedList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findMaterialFixedList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeMaterialFixedList = sltMaterialFixeds.filter((p: any) => isEmpty(p.id));
        if (removeMaterialFixedList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.materialFixedTableRef;
          if ($Xtable) {
            for (const removeRow of removeMaterialFixedList) {
              const index = materialFixedList.findIndex((item: any) => item == removeRow);
              materialFixedList.splice(index, 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function formatDateNYR(row) {
  if (!isEmpty(row.stopDate)) {
    return moment(row.stopDate).format('YYYY-MM-DD');
  } else {
    return '';
  }
}

// ------------------------------------------------------------
//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}
function getExpandedkeys() {
  for (const materialItem of materialItemTree) {
    getChildren(materialItem);
  }
}

function getChildren(obj: any) {
  const children = obj.children;
  if (obj.type == 'instrClass' || obj.type == 'instr') {
    //expandedkeys.push(obj.id);
  }
  if (!IsEmpty(children) && children.length > 0) {
    for (const ch of children) {
      getChildren(ch);
    }
  }
}
function computeCV(row: any) {
  row.cv = parseFloat(((row.sd / row.mean) * 100).toFixed(6));
}
function computeSD(row: any) {
  row.sd = parseFloat(((row.mean * row.cv) / 100).toFixed(6));
}
</script>

<style lang="scss" scoped>
#qcMaterialTargetDiv {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .splitpanes {
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }

      // 右侧保存按钮
      .saveBtn {
        float: right;
        margin: 5px 50px;
      }

      .el-tabs {
        height: 100%;

        :deep(.el-tabs__content) {
          padding: 0;
          height: calc(100% - 39px);

          .el-tab-pane {
            height: 100%;
          }

          // 最右侧质控靶值设定表格
          .tableBox {
            height: calc(100% - 40px);
          }
        }
      }
      .compute-button {
        background-color: #89d7fc;
      }
    }
  }
}
</style>
